package htmodels

import (
	"github.com/astaxie/beego/orm"
	"datapro/models"
)

func HTRecordAdd(record *models.Record) error {
	o := orm.NewOrm()
	_, err := o.Insert(record)
	return err
}

func HTRecordGetDetail(record *models.Record) error {
	o := orm.NewOrm()
	return o.Read(record)
}

func HTRecordGetCount(search string, searchFiled string, Status int, RecordType int) (int64, error) {
	o := orm.NewOrm()
	m := models.Record{}
	qb := o.QueryTable(m.TableName())
	if Status >= 0 {
		qb = qb.Filter(m.FN_Status(), Status)
	}
	if RecordType >= 0 {
		qb = qb.Filter(m.FN_RecordType(), RecordType)
	}
	count, err := qb.Filter(searchFiled + "__icontains", search).Count()
	return count, err
}

func HTRecordGetList(records *[]models.Record, fields []string, Status int, RecordType int, offset int64, limit int, search string, searchFiled string, orderby string) error {
	o := orm.NewOrm()
	m := models.Record{}
	qb := o.QueryTable(m.TableName())
	if Status >= 0 {
		qb = qb.Filter(m.FN_Status(), Status)
	}
	if RecordType >= 0 {
		qb = qb.Filter(m.FN_RecordType(), RecordType)
	}
	_, err := qb.Filter(searchFiled + "__icontains", search).OrderBy(orderby).Offset(offset).Limit(limit).All(records, fields...)
	return err
}

func HTRecordDelete(Ids []int64) (int64, error) {
	o := orm.NewOrm()
	m := models.Record{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Delete()
	return count, err
}
func HTRecordStatusChange(Ids []int64, status int) (int64, error) {
	o := orm.NewOrm()
	m := models.Record{}
	count, err := o.QueryTable(m.TableName()).Filter("Id" + "__in", Ids).Update(orm.Params{
		m.FN_Status(): status,
	})
	return count, err
}
func HTRecordUpdate(record *models.Record) error {
	o := orm.NewOrm()
	_, err := o.Update(record)
	return err
}